import React, { useState, useEffect } from 'react'
import { Button, Modal, message, Select, Radio, Form, Row, Col, Input } from 'antd'
import { BaseListPage, IBaseListPageProps, IBaseListPageState, UdModal, UdModalForm, uaaApp } from '../../../lib'
import { columnRenders } from '../../../lib/utils/columnRenders'
import { http } from '../../../lib/core/http'
import apis from '@/apis/UserManagement'
import { resetPassword, enableHandle } from '../common'
import EnableRadioGroup from '../component/EnableRadioGroup'

const confirm = Modal.confirm
const Option = Select.Option

const EnableBtnAuth = 'user_dealer_employee_manager_valid'
const UpdateBtnAuth = 'user_dealer_employee_manager_edit'
const ResetPasswordBtnAuth = 'user_dealer_employee_manager_setPassword'
const UntieBtnAuth = 'user_dealer_employee_manager_untie'

class DealerStaffList extends BaseListPage<IDealerStaffListProps, IDealerStaffListState> {
  protected saveParamsWithUrl: boolean = true

  private statusTranslate = {
    1: '启用',
    0: '禁用',
  }

  private statusOptions = [
    ...Object.keys(this.statusTranslate).map(key => ({ value: key, name: this.statusTranslate[key] })),
  ]

  constructor(props: IDealerStaffListProps) {
    super(props)

    this.state = {
      title: '经销商员工管理',
      queryApi: apis.DealerStaffList,
      conditions: [
        { id: 'userName', label: '员工姓名', labelCol: { span: 8 } },
        { id: 'phone', label: '员工手机号', labelCol: { span: 8 } },
        { id: 'agentName', label: '客户名称', labelCol: { span: 8 } },
        { id: 'agentCode', label: '客户编码', labelCol: { span: 8 } },
        // { id: 'roleName', label: '角色', labelCol: {span: 8} },
        {
          id: 'isValid',
          label: '状态',
          labelCol: { span: 8 },
          render: (
            <Select placeholder="请输入状态">
              {this.statusOptions.map(({ value, name }) => (
                <Option key={value} value={value}>
                  {name}
                </Option>
              ))}
            </Select>
          ),
        },
      ],
      rowKey: 'id',
      columns: [
        ['员工姓名', 'userName'],
        ['员工手机号', 'phone'],
        ['客户编码', 'agentCode'],
        ['客户名称', 'agentName'],
        ['角色', 'roleName'],
        ['状态', 'isValid', columnRenders.enum(this.statusTranslate), { minWidth: '30px' }],
        ['创建时间', 'createTime'],
        ['创建人', 'createBy'],
        ['最近修改时间', 'updateTime'],
        ['最近修改人', 'updateBy'],
        {
          title: '操作',
          dataIndex: 'operate',
          fixedWidth: '160px',
          allowCustomize: false,
          render: columnRenders.operate([
            {
              title: '编辑',
              auth: UpdateBtnAuth,
              action: (text: any, record: any) => this.setRoles(record),
              show: (text, model, index) =>{
                return model.roleName!=='经销商主账号'
              },
            },
            {
              title: '重置密码',
              auth: ResetPasswordBtnAuth,
              action: (text: any, record: any) => {
                // 设置默认的重置密码
                record.password = `Jxsmh@${parseInt(record.agentCode)}`
                confirm({
                  title: '确定要重置登录密码吗？',
                  content: (
                    <Form labelCol={{ span: 6 }} wrapperCol={{ span: 12 }}>
                      <Row gutter={24}>
                        <Col>
                          <Form.Item label={'设置密码'} required={true}>
                            <Input
                              onChange={e => {
                                record.password = e.target.value
                              }}
                              defaultValue={`${record.password}`}
                            />
                          </Form.Item>
                        </Col>
                      </Row>
                    </Form>
                  ),
                  onOk: () => {
                    if (!record.password) {
                      message.error('请填写修改的密码')
                      return Promise.reject('请填写修改的密码')
                    }
                    const reg: any = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/
                    if (!reg.test(record.password)) {
                      message.error('密码至少包含大写字母，小写字母，数字，且不少于8位')
                      return Promise.reject('密码至少包含大写字母，小写字母，数字，且不少于8位')
                    }
                    this.resetPassword(record)
                  },
                })
              },
            },
            {
              title: 'unionID解绑',
              auth: UntieBtnAuth,
              action: (text: any, record: any) => {
                confirm({
                  title: '确定要解绑unionID吗？',
                  onOk: () => {
                    return this.untie(record.id)
                  },
                })
              },
            },
          ]),
        },
      ],
      leftBtns: [
        uaaApp.canUse(EnableBtnAuth) &&
          (() => (
            <Button type="primary" disabled={!this.existSelectedRow()} onClick={() => this.enableHandle(true)}>
              启用
            </Button>
          )),
        uaaApp.canUse(EnableBtnAuth) &&
          (() => (
            <Button disabled={!this.existSelectedRow()} onClick={() => this.enableHandle(false)}>
              禁用
            </Button>
          )),
      ],
      tableProps: {
        rowSelection: !uaaApp.canUse(EnableBtnAuth) ? null : {},
        className: 'nowarp-th',
      },
    }
  }

  public componentWillMount() {
    super.componentWillMount()
  }

  untie = (userId: any) => {
    http.post(apis.untieUserUnionID, { userId }).then(() => {
      message.success('解绑成功')
      this.query()
    })
  }

  private setRoles = row => {
    if (!Array.isArray(row.roleId)) {
      row.roleId = row.roleId?.split(',')
    }
    UdModal.open({
      title: '编辑',
      content: (
        <UdModalForm
          items={[
            { id: 'userName', label: '员工姓名', render: <div>{row['userName']}</div> },
            { id: 'phone', label: '员工手机号', render: <div>{row['phone']}</div> },
            { id: 'agentCode', label: '客户编码', render: <div>{row['agentCode']}</div> },
            { id: 'agentName', label: '客户名称', render: <div>{row['agentName']}</div> },
            /* { id: 'roleId', label: '角色', render: ()=>(
          <Select mode="multiple">
            {roleList.map(({value, name})=><Option key={value} value={value}>{name}</Option>)}
          </Select>
        )}, */
            { id: 'roleId', label: '角色', render: <RoleSelectCm agentCode={row?.agentCode} /> },
            { id: 'isValid', label: '状态', render: <RadioCm /> },
          ]}
          values={row}
        />
      ),
      onOk: values => {
        // accountType:1 表示经销商
        const params = { id: row.id, depmentId: row.depmentId, accountType: 1, ...values }
        return http.post(apis.UpdateDealerStaff, params).then(res => {
          http.get(apis.pushUpdateDealerZdByDealerCode, { params: { dealerCode: row?.agentCode } }).then(resp => {})
          message.success('编辑成功')
          this.query()
        })
      },
    })
  }

  private resetPassword = row => {
    const { id, password } = row
    return resetPassword({
      url: apis.ResetPasswordDealerStaff,
      params: { id, password },
    })
  }

  private enableHandle = flag => {
    const idList = this.state.selectedRowKeys?.join(',')
    const isValid = flag ? 1 : 0
    enableHandle({
      flag,
      url: apis.EnableInternalStaff,
      params: {
        idList,
        isValid,
      },
      cb: () => {
        this.query()
      },
    })
  }
}

interface IDealerStaffListProps extends IBaseListPageProps {}

interface IDealerStaffListState extends IBaseListPageState {}

export default DealerStaffList

function RoleSelectCm(props) {
  const [roleList, setRoleList] = useState([])
  useEffect(() => {
    getRoleList(props.agentCode)
    return () => {
      setRoleList([])
    }
  }, [props.agentCode])

  const getRoleList = agentCode => {
    const params = { agentCode }
    http.get(apis.DealerRoleSelectList, { params }).then(res => {
      const roleList = res.data.map(({ id, roleName }) => ({ value: String(id), title: roleName }))
      setRoleList(roleList)
    })
  }
  return (
    <Select
      getPopupContainer={triggerNode => triggerNode.parentElement}
      placeholder="请选择角色"
      mode="multiple"
      optionFilterProp="children"
      onChange={props.onChange}
      value={props.value}
    >
      {roleList.map(({ value, title }) => (
        <Option key={value} value={value}>
          {title}
        </Option>
      ))}
    </Select>
  )
}

function RadioCm(props) {
  const options = [
    { value: '0', title: '禁用' },
    { value: '1', title: '启用' },
  ]
  return <EnableRadioGroup options={options} onChange={props.onChange} value={props.value} />
}
